from django import http
from django.http import JsonResponse
from django.views import View
from users.models import User

class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        """
        :param request: 请求对象
        :param username: 用户名
        :return: JSON
        """
        # 获取数据库中该用户名对应的个数
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '访问数据库失败',
            })

        # 拼接参数, 返回:
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'OK',
                                  'count': count})


class MobileCountView(View):

    def get(self,request,mobile):
        '''
                判断电话是否重复, 返回对应的个数
                :param request:
                :param mobile:
                :return:
                '''
        # 1.从数据库中查询 mobile 对应的个数
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '访问数据库失败',
            })
        # 2.拼接参数, 返回
        return http.JsonResponse({
            'code': 0,
            'errmsg': 'OK',
            'count': count
        })